<template>
  <div class="p-4 bg-gray-50 min-h-screen max-w-7xl mx-auto">
    <!-- 顶部标题和查询区域 -->
    <div class="mb-5 bg-white rounded-lg shadow-sm p-4">
      <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-4">
        <h2 class="text-2xl font-bold text-gray-800 mb-3 sm:mb-0">
          签到统计
          <span class="text-base text-gray-500 ml-2">Task #{{ taskId }}</span>
        </h2>

        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['manage:check_task:export']"
        >导出</el-button>
        <!--        <div class="flex items-center gap-3">-->
        <!--          <el-input-->
        <!--              v-model="taskId"-->
        <!--              placeholder="输入任务ID"-->
        <!--              class="!w-48"-->
        <!--              :prefix-icon="Search"-->
        <!--              size="large"-->
        <!--          />-->
        <!--          <el-button-->
        <!--              @click="fetchData"-->
        <!--              type="primary"-->
        <!--              :loading="loading"-->
        <!--              size="large"-->
        <!--          >-->
        <!--            查询-->
        <!--          </el-button>-->
        <!--        </div>-->
      </div>
    </div>
    <!--    <qc></qc>-->
    <qc v-if="checkType==3"></qc>

    <!-- 统计信息卡片 -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-5 auto-rows-fr">
      <!-- 已签到卡片 -->
      <div class="bg-white rounded-lg shadow-sm p-4 hover:shadow-md transition-shadow h-full">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm text-gray-500">已签到</p>
            <h3 class="text-2xl font-bold text-green-600 mt-1">
              {{ checkedInStudents.length }}
            </h3>
          </div>
          <div class="p-2 bg-green-100 rounded-lg">
            <el-icon class="text-green-600 text-xl"><Check /></el-icon>
          </div>
        </div>
        <div class="mt-2">
          <div class="text-sm text-gray-500">
            签到率：{{ ((checkedInStudents.length / checkList.length) * 100).toFixed(1) }}%
          </div>
        </div>
      </div>

      <!-- 未签到卡片 -->
      <div class="bg-white rounded-lg shadow-sm p-4 hover:shadow-md transition-shadow h-full">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm text-gray-500">未签到</p>
            <h3 class="text-2xl font-bold text-red-600 mt-1">
              {{ notCheckedInStudents.length }}
            </h3>
          </div>
          <div class="p-2 bg-red-100 rounded-lg">
            <el-icon class="text-red-600 text-xl"><Close /></el-icon>
          </div>
        </div>
        <div class="mt-2">
          <div class="text-sm text-gray-500">
            未签到率：{{ ((notCheckedInStudents.length / checkList.length) * 100).toFixed(1) }}%
          </div>
        </div>
      </div>

      <!-- 总人数卡片 -->
      <div class="bg-white rounded-lg shadow-sm p-4 hover:shadow-md transition-shadow h-full">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm text-gray-500">总人数</p>
            <h3 class="text-2xl font-bold text-blue-600 mt-1">
              {{ checkList.length }}
            </h3>
          </div>
          <div class="p-2 bg-blue-100 rounded-lg">
            <el-icon class="text-blue-600 text-xl"><User /></el-icon>
          </div>
        </div>
        <div class="mt-2">
          <div class="text-sm text-gray-500">
            班级数：{{ getUniqueClassCount() }}
          </div>
        </div>
      </div>

      <!-- 签到进度卡片 -->
      <div class="bg-white rounded-lg shadow-sm p-4 hover:shadow-md transition-shadow h-full">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm text-gray-500">签到进度</p>
            <h3 class="text-2xl font-bold text-purple-600 mt-1">
              {{ ((checkedInStudents.length / checkList.length) * 100).toFixed(1) }}%
            </h3>
          </div>
          <div class="p-2 bg-purple-100 rounded-lg">
            <el-icon class="text-purple-600 text-xl"><Timer /></el-icon>
          </div>
        </div>
        <div class="mt-2">
          <el-progress
              :percentage="Number(((checkedInStudents.length / checkList.length) * 100).toFixed(1))"
              :color="progressColor"
          />
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="bg-white rounded-lg shadow-sm">
      <el-tabs v-model="activeTab" class="px-4 pt-2">
        <el-tab-pane label="已签到学生" name="checked">
          <div class="p-4">
            <el-table
                :data="checkedInStudents"
                style="width: 100%"
                size="large"
                :header-cell-style="{
                background: '#f8fafc',
                color: '#1e293b',
                height: '50px',
                fontWeight: 'bold'
              }"
            >
              <el-table-column prop="studentNumber" label="学号" min-width="120" />
              <el-table-column prop="studentName" label="姓名" min-width="100">
                <template #default="{ row }">
                  <span class="font-medium">{{ row.studentName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="className" label="班级" min-width="160">
                <template #default="{ row }">
                  <el-tag size="default" effect="plain">{{ row.className }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="checkTime" label="签到时间" min-width="180">
                <template #default="{ row }">
                  <div class="flex items-center">
                    <el-icon class="mr-2 text-gray-400"><Timer /></el-icon>
                    <span>{{ formatDateTime(row.checkTime) }}</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="未签到学生" name="not-checked">
          <div class="p-4">
            <el-table
                :data="notCheckedInStudents"
                style="width: 100%"
                size="large"
                :header-cell-style="{
                background: '#f8fafc',
                color: '#1e293b',
                height: '50px',
                fontWeight: 'bold'
              }"
            >
              <el-table-column prop="studentNumber" label="学号" min-width="120" />
              <el-table-column prop="studentName" label="姓名" min-width="100">
                <template #default="{ row }">
                  <span class="font-medium">{{ row.studentName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="className" label="班级" min-width="160">
                <template #default="{ row }">
                  <el-tag size="default" effect="plain" type="info">{{ row.className }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="checkStatus" label="状态" min-width="120">
                <template #default="{ row }">
                  <el-tag type="danger" effect="dark" class="flex items-center w-24 justify-center">
                    <el-icon class="mr-1"><Warning /></el-icon>
                    {{ row.checkStatus }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted } from 'vue' // 确保导入了 onMounted
import { ref, computed } from 'vue'
import { getCheckStatus } from '@/api/check'
import { Search, Check, Close, User, Timer, Warning } from '@element-plus/icons-vue'
import {
  getCheckTaskById
} from "@/api/manage/check_task.js";

// const taskId = ref(104)
const checkList = ref([])
const activeTab = ref('checked')
const loading = ref(false)

const checkedInStudents = computed(() => {
  return checkList.value.filter(student => student.checkStatus === '已签到')
})

const notCheckedInStudents = computed(() => {
  return checkList.value.filter(student => student.checkStatus === '未签到')
})

// 进度条颜色
const progressColor = computed(() => {
  const percentage = (checkedInStudents.value.length / checkList.value.length) * 100
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
})

const getUniqueClassCount = () => {
  const uniqueClasses = new Set(checkList.value.map(student => student.className))
  return uniqueClasses.size
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}


import { useRoute } from 'vue-router';

const route = useRoute();
const taskId = route.query.taskId; // 获取查询参数
console.log(taskId)

// const fetchData = async () => {
//   loading.value = true
//   try {
//     const res = await getCheckStatus(taskId)
//     checkList.value = res
//   } catch (error) {
//     console.error('获取数据失败:', error)
//     ElMessage.error('获取数据失败')
//   } finally {
//     loading.value = false
//   }
//
// const checkType = ref(null)
//
//   try {
//     const res = await getCheckTaskById(taskId)
//     console.log(res)
//     checkType.value = res.taskType
//     console.log(checkType.value===0)
//   } catch (error) {
//     console.error('获取数据失败:', error)
//     ElMessage.error('获取数据失败')
//   }
// }
const checkType = ref(null) // 初始值设为 null 是合理的

const fetchData = async () => {
  loading.value = true
  try {
    // 同时获取两个接口数据
    const [statusRes, taskRes] = await Promise.all([
      getCheckStatus(taskId),
      getCheckTaskById(taskId)
    ])

    checkList.value = statusRes
    checkType.value = taskRes.taskType // 这里赋值会自动触发模板更新
    console.log(checkType.value)
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})

onMounted(() => {
  fetchData()
})
//
// const fetchData = async () => {
//   try {
//     const res = await getCheckTaskById(taskId.value)
//     checkTask.value = res
//   } catch (error) {
//     console.error('获取数据失败:', error)
//     ElMessage.error('获取数据失败')
//   }
// }

const { proxy } = getCurrentInstance();


/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('manage/check_task/export', {
//     taskId:101
//   }, `check_task_${new Date().getTime()}.xlsx`)
// }
/** 导出按钮操作 */
function handleExport() {
  const taskId = 101;
  proxy.download(`/api/check/status/export/${taskId}`, {}, `check_task_${new Date().getTime()}.xlsx`)
}




import qc from '@/components/qc.vue'
import {ElMessage} from "element-plus";

</script>

<style scoped>
:deep(.el-tabs__nav) {
  padding-left: 1rem;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}
</style>